package com.breakfast.fun.ui.user.order;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.BounceInterpolator;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.breakfast.fun.Constant;
import com.breakfast.fun.R;
import com.breakfast.fun.adapter.other.CommFragmentPagerAdapter;
import com.breakfast.fun.base.BaseActivity;
import com.breakfast.fun.event.ShowCouponEvent;
import com.breakfast.fun.util.Api;
import com.breakfast.fun.util.L;
import com.breakfast.fun.util.SharedUtil;
import com.breakfast.fun.view.widget.TitleBarView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.wechat.friends.Wechat;

public class UserOrderActivity extends BaseActivity<UserOrderPresenter, UserOrderModel> implements UserOrderContract.View {


    @Bind(R.id.tbv_user_order)
    TitleBarView tbvUserOrder;
    @Bind(R.id.tl_user_order)
    TabLayout tlUserOrder;
    @Bind(R.id.vp_user_order)
    ViewPager vpUserOrder;
    @Bind(R.id.iv_close_coupon)
    ImageView mIvCloseCoupon;
    @Bind(R.id.btn_coupon_send)
    Button mBtnCouponSend;
    @Bind(R.id.fl_coupon)
    FrameLayout mFlCoupon;
    @Bind(R.id.activity_coupon)
    RelativeLayout mActivityCoupon;
    @Bind(R.id.ll_user_order)
    LinearLayout mLlUserOrder;

    private String orderNo;

    @Override
    public int getLayoutId() {
        return R.layout.activity_user_order;
    }

    @Override
    public void initView() {

        EventBus.getDefault().register(this);

        orderNo = getIntent().getStringExtra("orderNo");
        L.d("orderNo:" + orderNo);

        mIvCloseCoupon.setOnClickListener(v -> {
            mActivityCoupon.clearAnimation();
            mActivityCoupon.setVisibility(View.GONE);
        });

        mActivityCoupon.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });

        mBtnCouponSend.setOnClickListener(v -> {
            //访问接口，跳转
            presenter.couponShare(Constant.getUserData().getMobile(),orderNo);
            mActivityCoupon.clearAnimation();
            mActivityCoupon.setVisibility(View.GONE);
        });


        tbvUserOrder.setTitleNoRight("我的订单");
        tbvUserOrder.setBack(this);

        tlUserOrder.addTab(tlUserOrder.newTab().setText("早餐订单"));
        tlUserOrder.addTab(tlUserOrder.newTab().setText("商城订单"));

        List<Fragment> list = new ArrayList<>();
        list.add(new BFOrderFragment());
        list.add(new MallOrderFragment());

        CommFragmentPagerAdapter adapter = new CommFragmentPagerAdapter(getSupportFragmentManager(), list);
        vpUserOrder.setAdapter(adapter);

        tlUserOrder.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                //点击TabLayout联动ViewPager
                vpUserOrder.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        vpUserOrder.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //切换viewpager时联动tab
                if (tlUserOrder.getTabCount() > 0) {
                    tlUserOrder.getTabAt(position).select();
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        if (getIntent().getBooleanExtra("isFromMall", false)) {
            tlUserOrder.getTabAt(1).select();
            vpUserOrder.setCurrentItem(1);
        }


    }

    private void showCouponShare(View targetView,View rootView) {
        Animation animation = AnimationUtils.loadAnimation(this, R.anim.gift_activity_anim);
        animation.setInterpolator(new BounceInterpolator());
        animation.setDuration(1000);
        animation.setFillAfter(true);
        targetView.setAnimation(animation);
        animation.start();
        rootView.setVisibility(View.VISIBLE);
    }

    private void showShare(String platform) {
        OnekeyShare oks = new OnekeyShare();

        //关闭sso授权
        //oks.disableSSOWhenAuthorize();

        if (platform != null) {
            oks.setPlatform(platform);
        }

        oks.setSilent(true);
        // 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        // oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle("我点了1份早范早餐，送你无门槛现金券！");
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl("http://m.52letsgo.com/themes/default/saomiao.php");
        // text是分享文本，所有平台都需要这个字段
//        oks.setText("注册时请输出邀请码：" + SharedUtil.getString(context, "recommendCode") + "\n");
        //分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
        oks.setText("每一天，我希望和你一起吃【早范早餐】！");
        oks.setImageUrl("http://static.52letsgo.cn/zz/ic_share.png");
        /*Uri uri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                + context.getResources().getResourcePackageName(R.drawable.ic_share) + "/" +
                context.getResources().getResourceTypeName(R.drawable.ic_share) + "/" +
                context.getResources().getResourceEntryName(R.drawable.ic_share));
        oks.setImagePath(uri.getPath());*/

        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl(Api.SHARE_URL + "?orderId=" + orderNo);
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        //oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
//        oks.setSite("早范邀请码:" + SharedUtil.getString(context, "recommendCode"));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://m.52letsgo.com/themes/default/saomiao.php");

// 启动分享GUI
        oks.show(this);
    }

    @Override
    public void showCouponShare() {

        ShareSDK.initSDK(UserOrderActivity.this);
        Platform platform = ShareSDK.getPlatform(Wechat.NAME);
        showShare(platform.getName());
    }

    @Subscribe
    public void onEvent(ShowCouponEvent event) {
        if (event.isNeedShowCouponShare()) {
            if(getIntent().getBooleanExtra("isFromPay",false))
                showCouponShare(mFlCoupon,mActivityCoupon);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
